package com.apes.framework.query.lib;

import com.apes.framework.query.lib.JPAConditionSqlCallback;
import com.apes.framework.query.lib.PubToolUtil;
import com.apestech.api.condition.ConditionExec;
import com.apestech.api.query.sys.SysSql;
import com.apestech.api.xml.esb.EsbUtil;
import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringFuncUtil;
import com.apestech.framework.xml.plugin.modul.QryConfig;
import com.apestech.framework.xml.plugin.modul.SysCondition;
import com.apestech.framework.xml.table.modul.Tables;

import java.util.ArrayList;
import java.util.Map;

public class BaseQuery extends StringFuncUtil {

    private JSONObject json;
    private SqlSession session;
    private String key;   //EXE_CONDITION, EXE_DIMENSION, condition.bill.query, condition.exec.query
    private String type;  //queryId,  sql, jsonarray
    private String way;   //联想输入， 弹窗查询， 查询功能， 操作查询
    private ArrayList<String> querylist;

    private String queryId;
    private String sysField=null;
    private String sysKey=null;
    private String sysPurpose=null;
    private QryConfig config=null;
    private JSONArray gridheader;
    private String conditionId=null;


    public BaseQuery(JSONObject json) throws Exception {
        querylist=new ArrayList<String>();
        querylist.add("condition.bill.query");
        querylist.add("condition.exec.query");
        querylist.add("condition.exec.query.stop");
        this.json=json;
        queryId=json.getString("queryid");
        if(json.get("size")!=null && json.getInteger("size")>0) json.put("page",json.getInteger("page")+1);
        if(querylist.contains(queryId)){
            config= PubToolUtil.getQryConfig(null);
        } else {
            config=PubToolUtil.getQryConfig(queryId);
        }
        conditionId=json.getString("conditionId");
    }

    public void query() throws Exception {
        if(conditionId==null){
            conditionQry();
            fieldQry();
        } else {
//            ConditionExec exec=new ConditionExec(session, conditionId);
            //json.put("sql",exec.getexecTabSql(mid, SysSql.getConditionRoleSql(json.getString("postId"), session)));
            //exec.getexecTabSql("001", SysSql.getConditionRoleSql(json.getString("postId"), session));
        }
    }

    private void conditionQry() throws Exception {
        //gridheader=JSON.toJSONArray(json.get("gridheader"));
        String cid=json.getString("CID");
        if(cid==null){
            return;
        }
        if(queryId!=null && !querylist.contains(queryId)){
            return;
        }
        if("condition.exec.query.stop".equals(queryId)) {
            queryId="condition.exec.query";
        }
        String mid=json.getString("MID");
        ConditionExec exec=new ConditionExec(session, cid);
        exec.setGridheader(gridheader);
        String cname=exec.getCondition().getName();
        String mname=exec.getCondition().getDimensionById(mid).getName();
        json.put("CNAME",cname);
        String tabname=exec.getCondition().getTableKey().getTabName(mid);
        json.put("MNAME", mname);
        json.put("sysTable",tabname);
        json.put("xlsName", cid+"-"+mid);
        json.put("sheetName", (cname+"-"+mname).replace("/","&"));
        session.setQryConfig(config);
        Tables tables=exec.getCondition().getTablesById(tabname);
        JSONObject r= EsbUtil.getTableIsField(tables);
        if(r!=null){
            json.put("SYS_IS_FIELD", r);
        }
        json=exec.getSelParam(mid,json);
        if("condition.bill.query".equals(queryId)){
            json.put("sql",exec.getbillQrySql(mid, SysSql.getConditionRoleSql(json.getString("postId"), session)));
            queryId=null;
            json.remove("queryid");
        } else if("condition.exec.query".equals(queryId)) {
            json.put("sql", exec.getexecTabSql(mid, SysSql.getConditionRoleSql(json.getString("postId"), session)));
            queryId = null;
            json.remove("queryid");
        } else if("strategy.queryImpTab".equals(queryId)){
            json.put("table","EXE_CONDITION_IMPORT");
            queryId=null;
            json.remove("queryId");
        } else {
            json.put("sql",exec.getzTabSql(mid, SysSql.getConditionRoleSql(json.getString("postId"), session)));
        }
        config.setSqlCallback(new JPAConditionSqlCallback(json, exec, session));
        json.put("gridheader", exec.getGridheader());
//                        JPAConditionQuery jQuery=new JPAConditionQuery(json, exec, session);
//                        JSONArray qlist=session.getForDDL().queryMasterTable(tables, json, jQuery);
//                        json.put("sysQueryList", qlist);
    }

    private void fieldQry() throws Exception {
        if(queryId==null){
            sysKey=json.getString("sysKey");
            sysField=json.getString("sysField");
            sysPurpose=json.getString("sysPurpose");
            if("EXE_CONDITION".equals(sysField) || "EXE_DIMENSION".equals(sysField) ){
                JSONArray qlist= null;
                JSONObject p=getQryMap(json);
                if("EXE_CONDITION".equals(sysField)) qlist= ConditionUtil.getConditionUsed(session, sysKey, p);
                else qlist=ConditionUtil.getDimension(session, sysKey, p);
                json.put("sysTable",sysField);
                json.put("sysQueryList",qlist);
            } else {
                if(sysKey!=null) {
                    sysKey=sysKey.trim();
                    json.put("sysKey_c", "%"+sysKey+"%");
                    json.put("sysKey", "%"+sysKey.toLowerCase()+"%");
                    setFieldParam();
                } else if(sysField!=null){
                    setFieldParam();
                }
            }
        }
    }

    private void setFieldParam() throws Exception {
        SysCondition sysCondition= LocalVariable.getConfig().getSysCondition(session);
        String s=session.getTheme()+"."+sysField;
        JSONObject m= sysCondition.getDimensionField(s);
        if(m==null) throw new RuntimeException("请先配置字段定义！");
        String sql=m.getString("sql");
        JSONObject rm=sysCondition.getRolefield(sysField);
        if(rm==null && m.get("copyField")!=null){
            rm=sysCondition.getRolefield(m.getString("copyField"));
        }
        if(rm!=null){
            //pp_belong pp_search pp_operate
            JSONObject cm=SysSql.getConditionRoleSql(json.getString("postId"), session);
            String type=cm.getString("type");
            if((","+type+",").indexOf(","+rm.getString("type")+",")>=0){
                sql="<auth field=\""+m.getString("field")+"\" type=\""+rm.getString("type")+"\" purpose=\""+sysPurpose+"\" exp=\""+sysField+"\"  />"+sql+"";
            }
        }
        json.put("sql", sql);
    }

    private JSONObject getQryMap(JSONObject param) throws Exception {
        if(param.get("condition")!=null){
            JSONObject p=new JSONObject();
            JSONArray list=JSON.toJSONArray(param.get("condition"));
            int len=list.size();
            for(int i=0; i<len; i++){
                JSONObject m=list.get(i);
                p.put(m.getString("field"), m.get("value"));
            }
            return p;
        } else return null;
    }

    public void setSession(SqlSession session) {
        this.session = session;
    }

    public SqlSession getSession() {
        return session;
    }

    public QryConfig getConfig() {
        return config;
    }

    public String getQueryId() {
        return queryId;
    }

    public JSONObject getJson() {
        return json;
    }
}
